package com.wx.sftp.impl;

import com.wx.sftp.Jcraft;
import com.wx.sftp.config.SaasFtpConf;
import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.Nullable;

import java.util.Properties;
import java.util.function.Function;

/**
 * @author 刘畅
 * @date 2018-12-04 19:21
 */
@Slf4j
@SuppressWarnings("unused")
public class BasicSaasFtp extends BaseSaasFtp {
  private static final int SFTP_TIMEOUT = 100000;
  private SaasFtpConf saasFtpConf;

  public BasicSaasFtp(SaasFtpConf saasFtpConf) {
    super(saasFtpConf);
    String host = saasFtpConf.getHost();
    String userName = saasFtpConf.getUserName();
    String password = saasFtpConf.getPassword();
    if (StringUtils.isBlank(host)) {
      throw new RuntimeException("host 不能为空");
    }
    if (StringUtils.isBlank(userName)) {
      throw new RuntimeException("userName 不能为空");
    }
    if (StringUtils.isBlank(password)) {
      throw new RuntimeException("password 不能为空");
    }
    this.saasFtpConf = saasFtpConf;
  }

  private Jcraft getJcraft() throws Exception {
    JSch jsch = new JSch();
    Session session = jsch.getSession(saasFtpConf.getUserName(),
        saasFtpConf.getHost(), saasFtpConf.getPort());

    session.setPassword(saasFtpConf.getPassword());

    Properties config = new Properties();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
    session.setTimeout(SFTP_TIMEOUT);
    session.connect();
    ChannelSftp sftp = (ChannelSftp) session.openChannel("sftp");
    sftp.connect();
    return new Jcraft(sftp, session);
  }

  @Nullable
  @Override
  <R> R apply(Function<ChannelSftp, R> function) {
    try (Jcraft jcraft = getJcraft()) {
      ChannelSftp sftp = jcraft.getSftp();
      return function.apply(sftp);
    } catch (Exception e) {
      log.warn("upload throw Exception:", e);
      return null;
    }
  }

  @Override
  public void close() {
    // The default implementation is a no-op.
  }
}
